package api

import (
	"service"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"pojo/vo"
	"constant"
	"pojo/form"
)

// 分类api管理
type CategoryApi struct {
	service *service.CategoryService
}

func NewCategoryApi(categoryService *service.CategoryService) *CategoryApi {

	return &CategoryApi{
		service: categoryService,
	}
}

// 保存分类信息
func (this *CategoryApi) Insert(ctx *gin.Context) {

	categoryForm := &form.CategoryForm{}
	ctx.Bind(categoryForm)

	err := this.service.InsertCategory(categoryForm)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存分类失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)

}

// 查询所有父级分类
func (this *CategoryApi) ListParents(ctx *gin.Context) {

	result := this.service.QueryCategoriesParents()

	ctx.JSON(http.StatusOK, result)
}

// 查询管理员列表
func (this *CategoryApi) List(ctx *gin.Context) {

	result := this.service.QueryCategories()

	ctx.JSON(http.StatusOK, result)
}

// 删除分类信息
func (this *CategoryApi) Delete(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	err := this.service.DeleteCategory(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "删除分类失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 根据ID查询分类信息
func (this *CategoryApi) Find(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	category, err := this.service.FindCategory(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "查询分类失败"
	} else {
		result = constant.SUCCESS
		result.Info = category
	}

	ctx.JSON(http.StatusOK, result)
}

// 修改分类信息
func (this *CategoryApi) Update(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)
	categoryForm := &form.CategoryForm{}
	ctx.Bind(categoryForm)
	categoryForm.Id = id

	err := this.service.UpdateCategory(categoryForm)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "保存分类失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)

}
